package com.lei.session.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lei.session.constant.UserConstant;
import com.lei.session.entity.Permission;
import com.lei.session.service.PermissionService;
import com.lei.session.service.UserService;
import com.lei.session.service.impl.PermissionServiceImpl;
import com.lei.session.service.impl.UserServiceImpl;
import com.lei.session.util.IpUtil;

public class UserServlet extends HttpServlet {
	private UserService userLoginService = new UserServiceImpl();
	private PermissionService permission= new PermissionServiceImpl();
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		String verifyCode = req.getParameter("verifyCode");
		String sessionVerifyCode = (String) req.getSession().getAttribute("verify");
		// 校验验证码
		if (sessionVerifyCode != null && !sessionVerifyCode.equals(verifyCode)) {
			req.setAttribute("msg", "验证码错误");
			req.getRequestDispatcher("session/login.jsp").forward(req, resp);
			return;
		}
		// 校验用户名密码
		if (userLoginService.login(userName, password,IpUtil.getIpAddress(req))) {
			req.getSession().setAttribute(UserConstant.LOGIN_INFO, userName);
			//设置权限
			setPremission(userName,req);
			resp.sendRedirect("LoginLogServlet?method=list");
		} else {
			req.setAttribute("msg", "账号或密码错误");
			req.getRequestDispatcher("session/login.jsp").forward(req, resp);
		}
	}
	private void setPremission(String userName,HttpServletRequest req) {
		HttpSession session = req.getSession();
		//获取用户权限
		List<Permission> premissionList = permission.listAll(userName);
		//设置到session
		session.setAttribute(UserConstant.USER_PRESSION, premissionList);
	}

}
